<template>
  <div class="questions">
    <el-card>
      <div slot="header">
        <span>题目管理</span>
        <div style="float: right">
          <el-button
            type="success"
            icon="el-icon-upload"
            @click="showImportDialog"
            >批量导入</el-button
          >
          <el-button
            type="warning"
            icon="el-icon-download"
            @click="exportQuestions"
            >批量导出</el-button
          >
          <el-button type="primary" icon="el-icon-plus" @click="showAddDialog"
            >新增题目</el-button
          >
        </div>
      </div>

      <!-- 左右分栏布局 -->
      <el-row :gutter="20">
        <!-- 左侧树形分类 -->
        <el-col :span="6">
          <el-card class="tree-card" shadow="never">
            <div slot="header" class="tree-header">
              <span>分类树形结构</span>
              <div class="tree-header-actions">
                <el-button
                  type="text"
                  size="mini"
                  @click="handleAddTopCategory"
                  title="新增顶级分类"
                >
                  <i class="el-icon-plus"></i>
                </el-button>
                <el-button type="text" size="mini" @click="expandAll">
                  <i class="el-icon-folder-opened"></i> 展开
                </el-button>
                <el-button type="text" size="mini" @click="collapseAll">
                  <i class="el-icon-folder"></i> 折叠
                </el-button>
              </div>
            </div>
            <el-tree
              ref="categoryTree"
              :data="categoryTreeData"
              :props="treeProps"
              node-key="id"
              :expand-on-click-node="false"
              :default-expand-all="false"
              @node-click="handleTreeNodeClick"
              class="category-tree"
              :highlight-current="true"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span class="tree-node-label">{{ node.label }}</span>
                <span class="tree-node-count" v-if="data.questionCount">
                  ({{ data.questionCount }})
                </span>
                <span class="tree-node-actions">
                  <el-button
                    type="text"
                    size="mini"
                    @click.stop="handleEditCategory(data)"
                    title="编辑分类"
                  >
                    <i class="el-icon-edit"></i>
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click.stop="handleAddSubCategory(data)"
                    v-if="data.level < 3"
                    title="添加子分类"
                  >
                    <i class="el-icon-plus"></i>
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click.stop="handleDeleteCategory(data)"
                    title="删除分类"
                  >
                    <i class="el-icon-delete"></i>
                  </el-button>
                </span>
              </span>
            </el-tree>
          </el-card>
        </el-col>

        <!-- 右侧题目列表 -->
        <el-col :span="18">
          <el-card class="list-card" shadow="never">
            <div slot="header" class="list-header">
              <span>题目列表</span>
              <span v-if="selectedCategory" class="selected-info">
                当前分类: {{ selectedCategory.name }}
              </span>
            </div>

            <!-- 搜索栏 -->
            <el-row :gutter="20" style="margin-bottom: 20px">
              <el-col :span="4">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索题目内容"
                  prefix-icon="el-icon-search"
                  clearable
                ></el-input>
              </el-col>
              <el-col :span="4">
                <el-input
                  v-model="searchConcept"
                  placeholder="搜索知识点"
                  prefix-icon="el-icon-search"
                  clearable
                ></el-input>
              </el-col>
              <el-col :span="4">
                <el-select
                  v-model="searchType"
                  placeholder="选择题型"
                  clearable
                >
                  <el-option
                    v-for="type in questionTypes"
                    :key="type.id"
                    :label="type.name"
                    :value="type.id"
                  ></el-option>
                </el-select>
              </el-col>
              <el-col :span="3">
                <el-select
                  v-model="searchDifficulty"
                  placeholder="选择难度"
                  clearable
                >
                  <el-option label="简单" :value="1"></el-option>
                  <el-option label="中等" :value="2"></el-option>
                  <el-option label="困难" :value="3"></el-option>
                </el-select>
              </el-col>
              <el-col :span="5">
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="resetSearch">重置</el-button>
              </el-col>
            </el-row>

            <!-- 题目列表 -->
            <el-table :data="questions" border style="width: 100%">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="title" label="题目标题" width="200">
                <template slot-scope="scope">
                  <el-tooltip :content="scope.row.title" placement="top">
                    <span>{{
                      scope.row.title.length > 25
                        ? scope.row.title.substring(0, 25) + "..."
                        : scope.row.title
                    }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column
                prop="categoryName"
                label="分类"
                width="120"
              ></el-table-column>
              <el-table-column prop="concept" label="知识点" width="100">
                <template slot-scope="scope">
                  <el-tag size="mini">{{ scope.row.concept }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                prop="type"
                label="题型"
                width="100"
                align="center"
              >
                <template slot-scope="scope">
                  <el-tag :type="getTypeTagType(scope.row.type)">{{
                    scope.row.questionTypeName
                  }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                prop="difficulty"
                label="难度"
                width="80"
                align="center"
              >
                <template slot-scope="scope">
                  <el-tag :type="getDifficultyTagType(scope.row.difficulty)">{{
                    getDifficultyText(scope.row.difficulty)
                  }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="tags" label="标签" width="120">
                <template slot-scope="scope">
                  <el-tag
                    v-for="tag in scope.row.tags
                      ? scope.row.tags.split(',')
                      : []"
                    :key="tag"
                    size="mini"
                    style="margin-right: 4px"
                  >
                    {{ tag }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                prop="createTime"
                label="创建时间"
                width="160"
              ></el-table-column>
              <el-table-column
                prop="updateTime"
                label="更新时间"
                width="160"
              ></el-table-column>
              <el-table-column
                label="操作"
                width="150"
                align="center"
                fixed="right"
              >
                <template slot-scope="scope">
                  <div class="action-buttons">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      @click="handleEdit(scope.row)"
                      title="编辑"
                    ></el-button>
                    <el-button
                      size="mini"
                      type="info"
                      icon="el-icon-view"
                      @click="handlePreview(scope.row)"
                      title="预览"
                    ></el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="handleDelete(scope.row)"
                      title="删除"
                    ></el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              style="margin-top: 20px; text-align: right"
            ></el-pagination>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 新增/编辑题目对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="900px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="questionForm"
        :rules="questionRules"
        ref="questionForm"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="题目标题" prop="title">
              <el-input
                v-model="questionForm.title"
                placeholder="请输入题目标题"
                maxlength="255"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="知识点" prop="concept">
              <el-input
                v-model="questionForm.concept"
                placeholder="请输入知识点，如：数组、链表"
                maxlength="100"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属分类" prop="categoryId">
              <el-cascader
                v-model="questionForm.categoryId"
                :options="categoryTreeOptions"
                :props="{ checkStrictly: true }"
                placeholder="请选择分类"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="题目类型" prop="questionTypeId">
              <el-select
                v-model="questionForm.questionTypeId"
                placeholder="请选择题型"
              >
                <el-option
                  v-for="type in questionTypes"
                  :key="type.id"
                  :label="type.name"
                  :value="type.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="题目难度" prop="difficulty">
              <el-radio-group v-model="questionForm.difficulty">
                <el-radio :label="1">简单</el-radio>
                <el-radio :label="2">中等</el-radio>
                <el-radio :label="3">困难</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签">
              <el-input
                v-model="questionForm.tags"
                placeholder="请输入标签，用逗号分隔"
                maxlength="255"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="题目内容" prop="content">
          <el-input
            type="textarea"
            v-model="questionForm.content"
            placeholder="请输入题目详细内容（题干）"
            :rows="4"
          ></el-input>
        </el-form-item>

        <!-- 选择题选项 -->
        <template
          v-if="
            ['single_choice', 'multiple_choice'].includes(
              getTypeCode(questionForm.questionTypeId)
            )
          "
        >
          <el-form-item label="题目选项" prop="options">
            <div
              v-for="(option, index) in questionForm.options"
              :key="index"
              style="margin-bottom: 10px"
            >
              <el-row :gutter="10">
                <el-col :span="2">
                  <el-tag>{{ String.fromCharCode(65 + index) }}</el-tag>
                </el-col>
                <el-col :span="18">
                  <el-input
                    v-model="option.content"
                    :placeholder="`选项${String.fromCharCode(65 + index)}`"
                  ></el-input>
                </el-col>
                <el-col :span="4">
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="removeOption(index)"
                    :disabled="questionForm.options.length <= 2"
                  ></el-button>
                </el-col>
              </el-row>
            </div>
            <el-button type="primary" size="mini" @click="addOption"
              >添加选项</el-button
            >
          </el-form-item>
        </template>

        <!-- 判断题选项 -->
        <template v-if="getTypeCode(questionForm.questionTypeId) === 'true_false'">
          <el-form-item label="题目选项" prop="options">
            <el-radio-group v-model="questionForm.options">
              <el-radio
                :label="[
                  { content: '正确', value: 'true' },
                  { content: '错误', value: 'false' },
                ]"
              >
                使用默认选项（正确/错误）
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </template>

        <!-- 排序题选项 -->
        <template v-if="getTypeCode(questionForm.questionTypeId) === 'ordering'">
          <el-form-item label="排序选项" prop="options">
            <div
              v-for="(option, index) in questionForm.options"
              :key="index"
              style="margin-bottom: 10px"
            >
              <el-row :gutter="10">
                <el-col :span="2">
                  <el-tag>{{ index + 1 }}</el-tag>
                </el-col>
                <el-col :span="18">
                  <el-input
                    v-model="option.content"
                    :placeholder="`排序项${index + 1}`"
                  ></el-input>
                </el-col>
                <el-col :span="4">
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="removeOption(index)"
                    :disabled="questionForm.options.length <= 2"
                  ></el-button>
                </el-col>
              </el-row>
            </div>
            <el-button type="primary" size="mini" @click="addOption"
              >添加排序项</el-button
            >
          </el-form-item>
        </template>

        <!-- 匹配题选项 -->
        <template v-if="getTypeCode(questionForm.questionTypeId) === 'matching'">
          <el-form-item label="匹配选项" prop="options">
            <el-row :gutter="20">
              <el-col :span="12">
                <h4>左侧选项</h4>
                <div
                  v-for="(option, index) in questionForm.options.left"
                  :key="index"
                  style="margin-bottom: 10px"
                >
                  <el-row :gutter="10">
                    <el-col :span="2">
                      <el-tag>{{ String.fromCharCode(65 + index) }}</el-tag>
                    </el-col>
                    <el-col :span="18">
                      <el-input
                        v-model="option.content"
                        :placeholder="`左侧选项${String.fromCharCode(
                          65 + index
                        )}`"
                      ></el-input>
                    </el-col>
                    <el-col :span="4">
                      <el-button
                        type="danger"
                        size="mini"
                        icon="el-icon-delete"
                        @click="removeMatchingOption('left', index)"
                        :disabled="questionForm.options.left.length <= 2"
                      ></el-button>
                    </el-col>
                  </el-row>
                </div>
                <el-button
                  type="primary"
                  size="mini"
                  @click="addMatchingOption('left')"
                  >添加左侧选项</el-button
                >
              </el-col>
              <el-col :span="12">
                <h4>右侧选项</h4>
                <div
                  v-for="(option, index) in questionForm.options.right"
                  :key="index"
                  style="margin-bottom: 10px"
                >
                  <el-row :gutter="10">
                    <el-col :span="2">
                      <el-tag>{{ index + 1 }}</el-tag>
                    </el-col>
                    <el-col :span="18">
                      <el-input
                        v-model="option.content"
                        :placeholder="`右侧选项${index + 1}`"
                      ></el-input>
                    </el-col>
                    <el-col :span="4">
                      <el-button
                        type="danger"
                        size="mini"
                        icon="el-icon-delete"
                        @click="removeMatchingOption('right', index)"
                        :disabled="questionForm.options.right.length <= 2"
                      ></el-button>
                    </el-col>
                  </el-row>
                </div>
                <el-button
                  type="primary"
                  size="mini"
                  @click="addMatchingOption('right')"
                  >添加右侧选项</el-button
                >
              </el-col>
            </el-row>
          </el-form-item>
        </template>

        <!-- 正确答案 -->
        <el-form-item label="正确答案" prop="answer">
          <!-- 单选题答案 -->
          <template v-if="getTypeCode(questionForm.questionTypeId) === 'single_choice'">
            <el-radio-group v-model="questionForm.answer">
              <el-radio
                v-for="(option, index) in questionForm.options"
                :key="index"
                :label="String.fromCharCode(65 + index)"
              >
                {{ String.fromCharCode(65 + index) }}
              </el-radio>
            </el-radio-group>
          </template>

          <!-- 多选题答案 -->
          <template v-if="getTypeCode(questionForm.questionTypeId) === 'multiple_choice'">
            <el-checkbox-group v-model="questionForm.answer">
              <el-checkbox
                v-for="(option, index) in questionForm.options"
                :key="index"
                :label="String.fromCharCode(65 + index)"
              >
                {{ String.fromCharCode(65 + index) }}
              </el-checkbox>
            </el-checkbox-group>
          </template>

          <!-- 判断题答案 -->
          <template v-if="getTypeCode(questionForm.questionTypeId) === 'true_false'">
            <el-radio-group v-model="questionForm.answer">
              <el-radio label="true">正确</el-radio>
              <el-radio label="false">错误</el-radio>
            </el-radio-group>
          </template>

          <!-- 填空题答案 -->
          <template v-if="getTypeCode(questionForm.questionTypeId) === 'fill_blank'">
            <el-input
              v-model="questionForm.answer"
              placeholder="请输入正确答案"
            ></el-input>
          </template>

          <!-- 代码题答案 -->
          <template v-if="getTypeCode(questionForm.questionTypeId) === 'coding'">
            <el-input
              type="textarea"
              v-model="questionForm.answer"
              placeholder="请输入正确答案代码"
              :rows="6"
            ></el-input>
          </template>

          <!-- 排序题答案 -->
          <template v-if="getTypeCode(questionForm.questionTypeId) === 'ordering'">
            <el-input
              v-model="questionForm.answer"
              placeholder="请输入正确排序，如：1,2,3,4"
            ></el-input>
          </template>

          <!-- 匹配题答案 -->
          <template v-if="getTypeCode(questionForm.questionTypeId) === 'matching'">
            <div
              v-for="(option, index) in questionForm.options.left"
              :key="index"
              style="margin-bottom: 10px"
            >
              <el-row :gutter="10">
                <el-col :span="4">
                  <span>{{ String.fromCharCode(65 + index) }} 对应：</span>
                </el-col>
                <el-col :span="8">
                  <el-select
                    v-model="questionForm.answer[index]"
                    placeholder="选择匹配项"
                  >
                    <el-option
                      v-for="(rightOption, rightIndex) in questionForm.options
                        .right"
                      :key="rightIndex"
                      :label="rightIndex + 1"
                      :value="rightIndex + 1"
                    ></el-option>
                  </el-select>
                </el-col>
              </el-row>
            </div>
            <div style="margin-top: 10px; color: #909399; font-size: 12px;">
              提示：为每个左侧选项选择对应的右侧选项，形成正确的匹配关系
            </div>
          </template>

          <!-- 简答题答案 -->
          <template v-if="getTypeCode(questionForm.questionTypeId) === 'short_answer'">
            <el-input
              type="textarea"
              v-model="questionForm.answer"
              placeholder="请输入参考答案"
              :rows="4"
            ></el-input>
          </template>

          <!-- 案例分析题答案 -->
          <template v-if="getTypeCode(questionForm.questionTypeId) === 'case_study'">
            <el-input
              type="textarea"
              v-model="questionForm.answer"
              placeholder="请输入案例分析答案"
              :rows="6"
            ></el-input>
          </template>
        </el-form-item>

        <!-- 代码题模板 -->
        <template v-if="getTypeCode(questionForm.questionTypeId) === 'coding'">
          <el-form-item label="代码模板">
            <el-input
              type="textarea"
              v-model="questionForm.template"
              placeholder="请输入代码模板"
              :rows="6"
            ></el-input>
          </el-form-item>
        </template>

        <el-form-item label="题目解析">
          <el-input
            type="textarea"
            v-model="questionForm.explanation"
            placeholder="请输入题目解析说明，帮助用户理解知识点"
            :rows="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      title="批量导入题目"
      :visible.sync="importDialogVisible"
      width="500px"
    >
      <el-form label-width="100px">
        <el-form-item label="文件格式">
          <el-radio-group v-model="importFormat">
            <el-radio label="excel">Excel</el-radio>
            <el-radio label="csv">CSV</el-radio>
            <el-radio label="json">JSON</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择文件">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            accept=".xlsx,.xls,.csv,.json"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              只能上传 xlsx/xls/csv/json 文件
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="downloadTemplate"
            >下载模板</el-button
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleImport">开始导入</el-button>
      </div>
    </el-dialog>

    <!-- 新增/编辑分类对话框 -->
    <el-dialog
      :title="categoryDialogTitle"
      :visible.sync="categoryDialogVisible"
      width="600px"
      @close="resetCategoryForm"
    >
      <el-form
        :model="categoryForm"
        :rules="categoryRules"
        ref="categoryForm"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="categoryForm.name"
            placeholder="请输入分类名称"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="父分类" prop="parentId">
          <el-select
            v-model="categoryForm.parentId"
            placeholder="请选择父分类"
            clearable
          >
            <el-option label="顶级分类" value=""></el-option>
            <el-option
              v-for="item in parentCategoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类层级" prop="level">
          <el-input-number
            v-model="categoryForm.level"
            :min="1"
            :max="3"
            disabled
          ></el-input-number>
          <span style="margin-left: 10px; color: #999">系统自动计算</span>
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input
            type="textarea"
            v-model="categoryForm.description"
            placeholder="请输入分类描述"
            :rows="3"
            maxlength="255"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="categoryForm.sort"
            :min="0"
            :max="9999"
            placeholder="数值越小越靠前"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="categoryDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleCategorySubmit"
          :loading="categorySubmitLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 题目预览对话框 -->
    <el-dialog
      title="题目预览"
      :visible.sync="previewDialogVisible"
      width="700px"
    >
      <div v-if="previewQuestion">
        <h3>{{ previewQuestion.title }}</h3>
        <p><strong>分类：</strong>{{ previewQuestion.categoryName }}</p>
        <p><strong>知识点：</strong>{{ previewQuestion.concept }}</p>
        <p><strong>题型：</strong>{{ previewQuestion.questionTypeName }}</p>
        <p>
          <strong>难度：</strong
          >{{ getDifficultyText(previewQuestion.difficulty) }}
        </p>
        <p><strong>标签：</strong>{{ previewQuestion.tags }}</p>

        <div style="margin: 15px 0">
          <h4>题目内容：</h4>
          <p>{{ previewQuestion.content }}</p>
        </div>

        <!-- 选择题选项 -->
        <div
          v-if="
            ['single_choice', 'multiple_choice'].includes(
              previewQuestion.type
            ) && previewQuestion.options
          "
        >
          <h4>选项：</h4>
          <div v-for="(option, index) in previewQuestion.options" :key="index">
            <p>{{ String.fromCharCode(65 + index) }}. {{ option.content }}</p>
          </div>
        </div>

        <!-- 判断题选项 -->
        <div
          v-if="
            previewQuestion.type === 'true_false' && previewQuestion.options
          "
        >
          <h4>选项：</h4>
          <div v-for="(option, index) in previewQuestion.options" :key="index">
            <p>{{ index + 1 }}. {{ option.content }}</p>
          </div>
        </div>

        <!-- 排序题选项 -->
        <div
          v-if="previewQuestion.type === 'ordering' && previewQuestion.options"
        >
          <h4>排序项：</h4>
          <div v-for="(option, index) in previewQuestion.options" :key="index">
            <p>{{ index + 1 }}. {{ option.content }}</p>
          </div>
        </div>

        <!-- 匹配题选项 -->
        <div
          v-if="previewQuestion.type === 'matching' && previewQuestion.options"
        >
          <h4>匹配项：</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <h5>左侧：</h5>
              <div
                v-for="(option, index) in previewQuestion.options.left"
                :key="index"
              >
                <p>
                  {{ String.fromCharCode(65 + index) }}. {{ option.content }}
                </p>
              </div>
            </el-col>
            <el-col :span="12">
              <h5>右侧：</h5>
              <div
                v-for="(option, index) in previewQuestion.options.right"
                :key="index"
              >
                <p>{{ index + 1 }}. {{ option.content }}</p>
              </div>
            </el-col>
          </el-row>
        </div>

        <div style="margin: 15px 0">
          <h4>正确答案：</h4>
          <p>
            {{
              Array.isArray(previewQuestion.answer)
                ? previewQuestion.answer.join(", ")
                : previewQuestion.answer
            }}
          </p>
        </div>

        <div v-if="previewQuestion.explanation">
          <h4>解析：</h4>
          <p>{{ previewQuestion.explanation }}</p>
        </div>

        <div v-if="previewQuestion.template">
          <h4>代码模板：</h4>
          <pre style="background: #f5f5f5; padding: 10px; border-radius: 4px">{{
            previewQuestion.template
          }}</pre>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getQuestionPage,
  createQuestion,
  updateQuestion,
  deleteQuestion,
  importQuestions,
  exportQuestions,
  getCategoryTree,
  getCategoryQuestionCount,
  createCategory,
  updateCategory,
  deleteCategory,
  getQuestionTypes,
} from "@/utils/api";

export default {
  name: "AdminQuestions",
  data() {
    return {
      searchKeyword: "",
      searchConcept: "",
      searchType: "",
      searchDifficulty: "",
      questions: [], // 从后端接口获取题目列表
      categoryOptions: [], // 从后端接口获取分类选项
      // categoryTreeOptions 将通过 computed 属性动态生成
      questionTypes: [], // 从后端接口获取题目类型
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: "新增题目",
      questionForm: {
        id: null,
        title: "",
        content: "",
        categoryId: [],
        concept: "",
        questionTypeId: null, // 新增题目类型ID字段
        difficulty: 2,
        tags: "",
        options: [
          { content: "", value: "A" },
          { content: "", value: "B" },
          { content: "", value: "C" },
          { content: "", value: "D" },
        ],
        answer: "",
        explanation: "",
        template: "",
      },
      questionRules: {
        title: [{ required: true, message: "请输入题目标题", trigger: "blur" }],
        content: [
          { required: true, message: "请输入题目内容", trigger: "blur" },
        ],
        categoryId: [
          { required: true, message: "请选择分类", trigger: "change" },
        ],
        concept: [{ required: true, message: "请输入知识点", trigger: "blur" }],
        questionTypeId: [
          { required: true, message: "请选择题型", trigger: "change" },
        ],
        difficulty: [
          { required: true, message: "请选择难度", trigger: "change" },
        ],
        answer: [
          { 
            required: true, 
            validator: (rule, value, callback) => {
              if (this.getTypeCode(this.questionForm.questionTypeId) === 'matching') {
                // 匹配题答案验证
                if (!Array.isArray(value) || value.length === 0) {
                  callback(new Error('请设置匹配题的正确答案'));
                  return;
                }
                // 检查是否所有左侧选项都有对应的答案
                const hasUnanswered = value.some(answer => answer === null || answer === undefined);
                if (hasUnanswered) {
                  callback(new Error('请为所有左侧选项选择对应的右侧选项'));
                  return;
                }
              } else {
                // 其他题型的答案验证
                if (!value || value.toString().trim() === '') {
                  callback(new Error('请输入正确答案'));
                  return;
                }
              }
              callback();
            }, 
            trigger: "blur" 
          },
        ],
      },
      importDialogVisible: false,
      importFormat: "excel",
      importFile: null,
      previewDialogVisible: false,
      previewQuestion: null,
      selectedCategory: null, // 当前选中的分类
      categoryTreeData: [], // 从后端接口获取分类树形数据
      treeProps: {
        label: "label",
        children: "children",
        isLeaf: "isLeaf", // 用于判断是否是叶子节点
      },
      // 分类管理相关
      categoryDialogVisible: false,
      categoryDialogTitle: "新增分类",
      categorySubmitLoading: false,
      categoryForm: {
        id: null,
        name: "",
        parentId: "",
        level: 1,
        description: "",
        sort: 0,
      },
      categoryRules: {
        name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          {
            min: 1,
            max: 100,
            message: "长度在 1 到 100 个字符",
            trigger: "blur",
          },
        ],
        description: [
          { max: 255, message: "描述不能超过255个字符", trigger: "blur" },
        ],
        sort: [{ required: true, message: "请输入排序值", trigger: "blur" }],
      },
    };
  },
  computed: {
    parentCategoryOptions() {
      return this.getParentCategoryOptions(this.categoryTreeData);
    },
    // 动态生成级联选择器需要的分类选项
    categoryTreeOptions() {
      return this.convertTreeToCascaderOptions(this.categoryTreeData);
    },
  },
  mounted() {
    this.loadCategoryTreeData();
    this.loadQuestionTypes(); // 加载题目类型

    // 处理路由参数
    const action = this.$route.query.action;
    if (action === "add-category") {
      this.handleAddTopCategory();
    }
  },
  watch: {
    "questionForm.questionTypeId": {
      handler() {
        this.resetQuestionForm();
      },
    },
  },
  methods: {
    // 根据题目类型ID获取类型代码
    getTypeCode(typeId) {
      const typeItem = this.questionTypes.find((item) => item.id === typeId);
      console.log("111");
      console.log(typeId);
      console.log(typeItem);
      return typeItem ? typeItem.code : typeId;
    },

    getTypeTagType(type) {
      const typeCode = this.getTypeCode(type);
      const typeMap = {
        single_choice: "primary",
        multiple_choice: "success",
        true_false: "info",
        fill_blank: "warning",
        coding: "danger",
        ordering: "warning",
        matching: "success",
        short_answer: "info",
        case_study: "danger",
      };
      return typeMap[typeCode] || "info";
    },
    getDifficultyTagType(difficulty) {
      const difficultyMap = {
        1: "success",
        2: "warning",
        3: "danger",
      };
      return difficultyMap[difficulty] || "info";
    },
    getDifficultyText(difficulty) {
      const difficultyMap = {
        1: "简单",
        2: "中等",
        3: "困难",
      };
      return difficultyMap[difficulty] || difficulty;
    },
    getCategoryName(id) {
      const category = this.categoryOptions.find((c) => c.id === id);
      return category ? category.name : "";
    },
    resetQuestionForm() {
      const type = this.questionForm.questionTypeId;

      // 根据题目类型ID查找对应的类型信息
      const typeItem = this.questionTypes.find((item) => item.id === type);
      const typeCode = typeItem ? typeItem.code : type;

      // 重置选项 - 根据题目类型动态设置
      if (["single_choice", "multiple_choice"].includes(typeCode)) {
        this.questionForm.options = [
          { content: "", value: "A" },
          { content: "", value: "B" },
          { content: "", value: "C" },
          { content: "", value: "D" },
        ];
      } else if (typeCode === "true_false") {
        this.questionForm.options = [
          { content: "正确", value: "true" },
          { content: "错误", value: "false" },
        ];
      } else if (typeCode === "ordering") {
        this.questionForm.options = [
          { content: "", value: "1" },
          { content: "", value: "2" },
          { content: "", value: "3" },
          { content: "", value: "4" },
        ];
      } else if (typeCode === "matching") {
        this.questionForm.options = {
          left: [
            { content: "", value: "A" },
            { content: "", value: "B" },
          ],
          right: [
            { content: "", value: "1" },
            { content: "", value: "2" },
          ],
        };
        // 初始化匹配题答案数组
        this.questionForm.answer = new Array(2).fill(null);
      } else {
        this.questionForm.options = null;
        // 重置答案
        this.questionForm.answer = "";
      }

      // 如果不是匹配题，重置答案
      if (typeCode !== "matching") {
        this.questionForm.answer = "";
      }

      // 重置模板
      if (typeCode !== "coding") {
        this.questionForm.template = "";
      }
    },
    addOption() {
      const type = this.questionForm.questionTypeId;
      const typeItem = this.questionTypes.find((item) => item.id === type);
      const typeCode = typeItem ? typeItem.code : type;

      if (["single_choice", "multiple_choice"].includes(typeCode)) {
        const nextChar = String.fromCharCode(
          65 + this.questionForm.options.length
        );
        this.questionForm.options.push({ content: "", value: nextChar });
      } else if (typeCode === "ordering") {
        const nextValue = this.questionForm.options.length + 1;
        this.questionForm.options.push({
          content: "",
          value: nextValue.toString(),
        });
      }
    },
    removeOption(index) {
      this.questionForm.options.splice(index, 1);

      // 重新设置选项值
      const type = this.questionForm.questionTypeId;
      const typeItem = this.questionTypes.find((item) => item.id === type);
      const typeCode = typeItem ? typeItem.code : type;

      if (["single_choice", "multiple_choice"].includes(typeCode)) {
        this.questionForm.options.forEach((option, idx) => {
          option.value = String.fromCharCode(65 + idx);
        });
      } else if (typeCode === "ordering") {
        this.questionForm.options.forEach((option, idx) => {
          option.value = (idx + 1).toString();
        });
      }
    },
    addMatchingOption(side) {
      if (side === "left") {
        const nextChar = String.fromCharCode(
          65 + this.questionForm.options.left.length
        );
        this.questionForm.options.left.push({ content: "", value: nextChar });
        // 为新增的左侧选项添加对应的答案
        this.questionForm.answer.push(null);
      } else {
        const nextValue = this.questionForm.options.right.length + 1;
        this.questionForm.options.right.push({
          content: "",
          value: nextValue.toString(),
        });
      }
    },
    removeMatchingOption(side, index) {
      if (side === "left") {
        this.questionForm.options.left.splice(index, 1);
        this.questionForm.options.left.forEach((option, idx) => {
          option.value = String.fromCharCode(65 + idx);
        });
        // 同时移除对应的答案
        this.questionForm.answer.splice(index, 1);
      } else {
        this.questionForm.options.right.splice(index, 1);
        this.questionForm.options.right.forEach((option, idx) => {
          option.value = (idx + 1).toString();
        });
        // 重新计算右侧选项的索引，并更新答案中对应的值
        if (this.questionForm.answer && Array.isArray(this.questionForm.answer)) {
          this.questionForm.answer.forEach((answer, idx) => {
            if (answer && answer > index + 1) {
              this.questionForm.answer[idx] = answer - 1;
            }
          });
        }
      }
    },
    handleSearch() {
      this.currentPage = 1;
      this.loadQuestions();
    },
    resetSearch() {
      this.searchKeyword = "";
      this.searchConcept = "";
      this.searchType = "";
      this.searchDifficulty = "";
      this.currentPage = 1;
      this.loadQuestions();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.loadQuestions();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadQuestions();
    },
    showAddDialog() {
      // 检查题目类型是否已加载
      if (!this.questionTypes || this.questionTypes.length === 0) {
        this.$message.error("题目类型未加载，请刷新页面重试");
        return;
      }

      this.dialogTitle = "新增题目";
      // 设置默认题目类型为第一个可用的类型
      const defaultType = this.questionTypes[0].id;

      this.questionForm = {
        id: null,
        title: "",
        content: "",
        categoryId: [],
        concept: "",
        questionTypeId: defaultType,
        difficulty: 2,
        tags: "",
        options: [
          { content: "", value: "A" },
          { content: "", value: "B" },
          { content: "", value: "C" },
          { content: "", value: "D" },
        ],
        answer: "",
        explanation: "",
        template: "",
      };
      
      // 根据题目类型初始化选项和答案
      this.resetQuestionForm();
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = "编辑题目";

      // 深拷贝数据，避免修改原数据
      const editData = JSON.parse(JSON.stringify(row));

      // 处理选项数据 - 如果是字符串格式，需要解析为对象
      if (editData.options && typeof editData.options === "string") {
        try {
          editData.options = JSON.parse(editData.options);
        } catch (error) {
          console.error("解析选项数据失败:", error);
          editData.options = [];
        }
      }

      // 处理答案数据 - 如果是字符串格式，需要解析
      if (editData.answer && typeof editData.answer === "string") {
        try {
          editData.answer = JSON.parse(editData.answer);
        } catch (error) {
          console.error("解析答案数据失败:", error);
          // 如果解析失败，保持原字符串
        }
      }

      this.questionForm = editData;
      
      // 如果是匹配题，确保答案数组正确初始化
      if (this.getTypeCode(this.questionForm.questionTypeId) === 'matching') {
        if (!Array.isArray(this.questionForm.answer)) {
          this.questionForm.answer = new Array(this.questionForm.options.left.length).fill(null);
        }
      }
      
      this.dialogVisible = true;
    },
    handlePreview(row) {
      // 深拷贝数据，避免修改原数据
      const previewData = JSON.parse(JSON.stringify(row));

      // 处理选项数据 - 如果是字符串格式，需要解析为对象
      if (previewData.options && typeof previewData.options === "string") {
        try {
          previewData.options = JSON.parse(previewData.options);
        } catch (error) {
          console.error("解析选项数据失败:", error);
          previewData.options = [];
        }
      }

      // 处理答案数据 - 如果是字符串格式，需要解析
      if (previewData.answer && typeof previewData.answer === "string") {
        try {
          previewData.answer = JSON.parse(previewData.answer);
        } catch (error) {
          console.error("解析答案数据失败:", error);
          // 如果解析失败，保持原字符串
        }
      }

      this.previewQuestion = previewData;
      this.previewDialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm(`确定要删除题目"${row.title}"吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const response = await deleteQuestion(row.id);
            if (response.code === 200) {
              this.$message.success("删除成功");
              this.loadQuestions();
              this.loadCategoryTreeData(); // 重新加载分类树以更新题目数量
            } else {
              this.$message.error(response.message || "删除失败");
            }
          } catch (error) {
            console.error("删除题目失败:", error);
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    async handleSubmit() {
      this.$refs.questionForm.validate(async (valid) => {
        if (valid) {
          try {
            // 处理表单数据
            const formData = { ...this.questionForm };
            delete formData.questionTypeName;

            // 处理分类ID
            if (
              Array.isArray(formData.categoryId) &&
              formData.categoryId.length > 0
            ) {
              formData.categoryId =
                formData.categoryId[formData.categoryId.length - 1];
            }

            // 处理选项数据
            if (formData.options) {
              formData.options = JSON.stringify(formData.options);
            }

            // 处理答案数据
            if (Array.isArray(formData.answer)) {
              formData.answer = JSON.stringify(formData.answer);
            }

            // 移除 categoryName 字段，只保留 categoryId
            delete formData.categoryName;

            let response;
            if (this.questionForm.id) {
              // 更新
              response = await updateQuestion(this.questionForm.id, formData);
            } else {
              // 新增
              response = await createQuestion(formData);
            }

            if (response.code === 200) {
              this.$message.success(
                this.questionForm.id ? "更新成功" : "添加成功"
              );
              this.dialogVisible = false;
              this.loadQuestions();
              this.loadCategoryTreeData(); // 重新加载分类树以更新题目数量
            } else {
              this.$message.error(response.message || "操作失败");
            }
          } catch (error) {
            console.error("保存题目失败:", error);
            this.$message.error("操作失败");
          }
        }
      });
    },
    showImportDialog() {
      this.importDialogVisible = true;
    },
    handleFileChange(file) {
      this.importFile = file;
      console.log("选择的文件:", file);
      return false; // 阻止自动上传
    },
    downloadTemplate() {
      // 这里应该下载对应的模板文件
      this.$message.success("模板下载中...");
    },
    async handleImport() {
      if (!this.importFile) {
        this.$message.warning("请选择要导入的文件");
        return;
      }

      try {
        const formData = new FormData();
        formData.append("file", this.importFile.raw);
        formData.append("format", this.importFormat);

        const response = await importQuestions(formData);
        if (response.code === 200) {
          this.$message.success("导入成功");
          this.importDialogVisible = false;
          this.loadQuestions();
          this.loadCategoryTreeData(); // 重新加载分类树以更新题目数量
        } else {
          this.$message.error(response.message || "导入失败");
        }
      } catch (error) {
        console.error("导入题目失败:", error);
        this.$message.error("导入失败");
      }
    },
    async exportQuestions() {
      try {
        const params = {
          categoryId: this.selectedCategory ? this.selectedCategory.id : null,
          keyword: this.searchKeyword,
          concept: this.searchConcept,
          type: this.searchType,
          difficulty: this.searchDifficulty,
        };

        const response = await exportQuestions(params);

        // 创建下载链接
        const blob = new Blob([response], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = `题目列表_${new Date()
          .toISOString()
          .slice(0, 10)}.xlsx`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        this.$message.success("导出成功");
      } catch (error) {
        console.error("导出题目失败:", error);
        this.$message.error("导出失败");
      }
    },
    async loadQuestions() {
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          keyword: this.searchKeyword,
          concept: this.searchConcept,
          type: this.searchType,
          difficulty: this.searchDifficulty,
          categoryId: this.selectedCategory ? this.selectedCategory.id : null,
        };

        console.log("加载题目列表，参数:", params);

        const response = await getQuestionPage(params);
        console.log("API响应:", response);

        if (response.code === 200) {
          // 处理返回的数据，解析选项和答案字段
          const records = response.data.records || [];
          this.questions = records.map((question) => {
            const processedQuestion = { ...question };

            // 处理选项数据
            if (
              processedQuestion.options &&
              typeof processedQuestion.options === "string"
            ) {
              try {
                processedQuestion.options = JSON.parse(
                  processedQuestion.options
                );
              } catch (error) {
                console.error("解析选项数据失败:", error);
                processedQuestion.options = [];
              }
            }

            // 处理答案数据
            if (
              processedQuestion.answer &&
              typeof processedQuestion.answer === "string"
            ) {
              try {
                processedQuestion.answer = JSON.parse(processedQuestion.answer);
              } catch (error) {
                console.error("解析答案数据失败:", error);
                // 如果解析失败，保持原字符串
              }
            }

            return processedQuestion;
          });

          this.total = response.data.total || 0;
          console.log("题目数据:", this.questions);
          console.log("总数:", this.total);
        } else {
          this.$message.error(response.message || "获取题目列表失败");
        }
      } catch (error) {
        console.error("加载题目列表失败:", error);
        this.$message.error("获取题目列表失败");
      }
    },
    async loadCategoryTreeData() {
      try {
        const response = await getCategoryTree();
        if (response.code === 200) {
          // 格式化树形数据
          this.categoryTreeData = this.formatTreeData(response.data);
          // 获取题目数量统计
          this.loadQuestionCount();
          
          // 页面加载时自动选择第一个根节点分类
          this.selectFirstRootCategory();
        } else {
          this.$message.error(response.message || "获取分类树形数据失败");
        }
      } catch (error) {
        console.error("加载分类树形数据失败:", error);
        this.$message.error("获取分类树形数据失败");
      }
    },

    // 页面加载时自动选择第一个根节点分类
    selectFirstRootCategory() {
      if (this.categoryTreeData && this.categoryTreeData.length > 0) {
        // 找到第一个根节点分类（level = 1 或 parentId 为空）
        const firstRootCategory = this.categoryTreeData.find(category => 
          category.level === 1 || !category.parentId
        );
        
        if (firstRootCategory) {
          // 自动选择第一个根节点分类
          this.selectedCategory = firstRootCategory;
          // 加载该分类下的题目
          this.loadQuestions();
          
          // 在树中高亮显示选中的分类
          this.$nextTick(() => {
            if (this.$refs.categoryTree) {
              this.$refs.categoryTree.setCurrentKey(firstRootCategory.id);
            }
          });
        }
      }
    },

    // 格式化树形数据
    formatTreeData(treeData) {
      if (!Array.isArray(treeData) || treeData.length === 0) {
        return [];
      }

      const formatNode = (node) => ({
        id: node.id,
        label: node.name,
        name: node.name,
        parentId: node.parentId || node.parent_id || null,
        level: node.level || 1,
        description: node.description || "",
        sort: node.sort || 0,
        createTime: node.createTime || node.create_time || "",
        updateTime: node.updateTime || node.update_time || "",
        questionCount: 0, // 初始化为0，后续会更新
        children: node.children ? node.children.map(formatNode) : [],
      });

      return treeData.map(formatNode);
    },

    // 将树形分类数据转换为级联选择器需要的格式
    convertTreeToCascaderOptions(treeData) {
      if (!Array.isArray(treeData) || treeData.length === 0) {
        return [];
      }

      const convertNode = (node) => ({
        value: node.id,
        label: node.name,
        children:
          node.children && node.children.length > 0
            ? node.children.map(convertNode)
            : undefined,
      });

      return treeData.map(convertNode);
    },

    // 加载题目数量统计
    async loadQuestionCount() {
      try {
        const response = await getCategoryQuestionCount();
        if (response.code === 200) {
          this.updateTreeQuestionCount(this.categoryTreeData, response.data);
        }
      } catch (error) {
        console.error("加载题目数量统计失败:", error);
      }
    },

    // 更新树形数据中的题目数量
    updateTreeQuestionCount(treeData, countData) {
      treeData.forEach((node) => {
        const count = countData[node.id] || 0;
        node.questionCount = count;
        if (node.children && node.children.length > 0) {
          this.updateTreeQuestionCount(node.children, countData);
        }
      });
    },

    // 加载题目类型
    async loadQuestionTypes() {
      try {
        const response = await getQuestionTypes();
        if (response.code === 200) {
          this.questionTypes = response.data || [];
          console.log("题目类型加载成功:", this.questionTypes);
        } else {
          console.error("获取题目类型失败:", response.message);
          this.$message.error(
            `获取题目类型失败: ${response.message || "未知错误"}`
          );
          throw new Error(response.message || "获取题目类型失败");
        }
      } catch (error) {
        console.error("加载题目类型失败:", error);
        this.$message.error(`加载题目类型失败: ${error.message || "网络错误"}`);
        throw error;
      }
    },
    handleTreeNodeClick(data) {
      this.selectedCategory = data;
      // 当分类节点被点击时，可以重新加载该分类下的题目
      this.currentPage = 1; // 重置当前页为1
      this.loadQuestions();
    },
    expandAll() {
      // 使用更可靠的方法展开所有节点
      if (this.$refs.categoryTree) {
        // 方法1：尝试使用 Element UI 的 expandAll 方法
        if (typeof this.$refs.categoryTree.expandAll === "function") {
          this.$refs.categoryTree.expandAll();
        }
        // 方法2：使用 setExpandedKeys 方法
        else if (
          typeof this.$refs.categoryTree.setExpandedKeys === "function"
        ) {
          const allKeys = this.getAllNodeKeys(this.categoryTreeData);
          this.$refs.categoryTree.setExpandedKeys(allKeys);
        }
        // 方法3：手动设置展开状态
        else {
          this.expandAllNodes(this.categoryTreeData);
        }
      }
    },

    // 折叠所有节点
    collapseAll() {
      // 使用更可靠的方法折叠所有节点
      if (this.$refs.categoryTree) {
        // 方法1：使用 setExpandedKeys 方法，传入空数组来折叠所有节点
        if (typeof this.$refs.categoryTree.setExpandedKeys === "function") {
          this.$refs.categoryTree.setExpandedKeys([]);
        }
        // 方法2：手动设置折叠状态
        else {
          this.collapseAllNodes(this.categoryTreeData);
        }
      }
    },

    // 获取所有节点的 key
    getAllNodeKeys(nodes) {
      let keys = [];
      if (!nodes || !Array.isArray(nodes)) return keys;

      nodes.forEach((node) => {
        keys.push(node.id);
        if (node.children && node.children.length > 0) {
          keys = keys.concat(this.getAllNodeKeys(node.children));
        }
      });
      return keys;
    },

    // 手动展开所有节点的辅助方法
    expandAllNodes(nodes) {
      if (!nodes || !Array.isArray(nodes) || !this.$refs.categoryTree) return;

      nodes.forEach((node) => {
        if (node.children && node.children.length > 0) {
          // 尝试直接设置展开状态
          try {
            if (
              this.$refs.categoryTree.store &&
              this.$refs.categoryTree.store.nodesMap
            ) {
              const treeNode = this.$refs.categoryTree.store.nodesMap[node.id];
              if (treeNode) {
                treeNode.expanded = true;
              }
            }
          } catch (error) {
            console.warn("设置节点展开状态失败:", error);
          }
          // 递归展开子节点
          this.expandAllNodes(node.children);
        }
      });
    },

    // 手动折叠所有节点的辅助方法
    collapseAllNodes(nodes) {
      if (!nodes || !Array.isArray(nodes) || !this.$refs.categoryTree) return;

      nodes.forEach((node) => {
        if (node.children && node.children.length > 0) {
          // 尝试直接设置折叠状态
          try {
            if (
              this.$refs.categoryTree.store &&
              this.$refs.categoryTree.store.nodesMap
            ) {
              const treeNode = this.$refs.categoryTree.store.nodesMap[node.id];
              if (treeNode) {
                treeNode.expanded = false;
              }
            }
          } catch (error) {
            console.warn("设置节点折叠状态失败:", error);
          }
          // 递归折叠子节点
          this.collapseAllNodes(node.children);
        }
      });
    },

    // 分类管理相关方法
    handleAddTopCategory() {
      this.categoryDialogTitle = "新增顶级分类";
      this.categoryForm = {
        id: null,
        name: "",
        parentId: "",
        level: 1,
        description: "",
        sort: 0,
      };
      this.categoryDialogVisible = true;
    },

    getParentCategoryOptions(categories, level = 0) {
      let options = [];
      categories.forEach((category) => {
        if (level < 2) {
          // 最多支持三级分类
          options.push({
            id: category.id,
            name: "　".repeat(level) + category.name,
          });
          if (category.children && category.children.length > 0) {
            options = options.concat(
              this.getParentCategoryOptions(category.children, level + 1)
            );
          }
        }
      });
      return options;
    },

    // 编辑分类
    handleEditCategory(data) {
      this.categoryDialogTitle = "编辑分类";
      this.categoryForm = {
        id: data.id,
        name: data.name,
        parentId: data.parentId || "",
        level: data.level,
        description: data.description || "",
        sort: data.sort,
      };
      this.categoryDialogVisible = true;
    },

    // 添加子分类
    handleAddSubCategory(data) {
      this.categoryDialogTitle = "新增子分类";
      this.categoryForm = {
        id: null,
        name: "",
        parentId: data.id,
        level: data.level + 1,
        description: "",
        sort: 0,
      };
      this.categoryDialogVisible = true;
    },

    // 删除分类
    handleDeleteCategory(data) {
      this.$confirm(
        `确定要删除分类"${data.name}"吗？删除后该分类下的所有子分类也将被删除。`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          try {
            const response = await deleteCategory(data.id);
            if (response.code === 200) {
              this.$message.success("删除成功");
              // 重新加载分类树数据
              this.loadCategoryTreeData();
              // 清除选中状态
              this.selectedCategory = null;
            } else {
              this.$message.error(response.message || "删除失败");
            }
          } catch (error) {
            console.error("删除分类失败:", error);
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 提交分类表单
    handleCategorySubmit() {
      this.$refs.categoryForm.validate(async (valid) => {
        if (valid) {
          this.categorySubmitLoading = true;
          try {
            let response;
            if (this.categoryForm.id) {
              // 更新
              response = await updateCategory(
                this.categoryForm.id,
                this.categoryForm
              );
            } else {
              // 新增
              response = await createCategory(this.categoryForm);
            }

            if (response.code === 200) {
              this.$message.success(
                this.categoryForm.id ? "更新成功" : "添加成功"
              );
              this.categoryDialogVisible = false;
              // 重新加载分类树数据
              this.loadCategoryTreeData();
            } else {
              this.$message.error(response.message || "操作失败");
            }
          } catch (error) {
            console.error("保存分类失败:", error);
            this.$message.error("操作失败");
          } finally {
            this.categorySubmitLoading = false;
          }
        }
      });
    },

    // 重置分类表单
    resetCategoryForm() {
      this.$refs.categoryForm && this.$refs.categoryForm.resetFields();
    },
  },
};
</script>

<style scoped>
.questions {
  padding: 20px;
}

.el-tag {
  margin-right: 4px;
}

.upload-demo {
  text-align: center;
}

.tree-card {
  min-height: 600px;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tree-header-actions {
  display: flex;
  gap: 8px;
}

.category-tree {
  height: 500px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.tree-node-label {
  flex: 1;
}

.tree-node-count {
  color: #909399;
  font-size: 12px;
}

.tree-node-actions {
  display: none;
}

.custom-tree-node:hover .tree-node-actions {
  display: flex;
  gap: 4px;
}

.list-card {
  min-height: 600px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-info {
  color: #409eff;
  font-size: 12px;
  font-weight: bold;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.action-buttons .el-button {
  margin: 0;
  padding: 7px 12px;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .el-col-6 {
    width: 35%;
  }
  .el-col-18 {
    width: 65%;
  }
}

@media (max-width: 768px) {
  .el-col-6,
  .el-col-18 {
    width: 100%;
    margin-bottom: 20px;
  }

  .tree-card,
  .list-card {
    height: auto;
  }

  .category-tree {
    height: 300px;
  }

  .action-buttons {
    gap: 4px;
  }

  .action-buttons .el-button {
    padding: 5px 8px;
  }
}
</style>
